package di

import (
	"net"
	"store-assistant/internal/service"
	pb "store-assistant/api/pbs"
	"google.golang.org/grpc"
)

type App struct {
	svc *service.WarehouseService 
	gsrv *grpc.Server 
}

func NewApp(svc *service.WarehouseService, srv *grpc.Server) (app *App, closeFunc func(), err error) {
	app = &App{
		svc: svc,
		gsrv: srv,
	}
	//注册grpc服务，开始服务 TODO从配置文件读端口
	lis, err := net.Listen("tcp", ":24751")
	if err != nil {
		panic("listen 24751 port failed") 
	}	

	pb.RegisterWarehouseServiceServer(app.gsrv, svc)
	
	closeFunc = func() {
		//TODO: 封装一个带超时控制的Cancel函数
		srv.GracefulStop()
	}

	go func(lis net.Listener) {
		if err := srv.Serve(lis); err != nil {
			panic(err)
		}
	}(lis)

	return 
}